package info.wegosoft.android.activity;

import info.wegosoft.R;
import info.wegosoft.android.model.Platform;
import info.wegosoft.android.qauth.sina.OAuthConstant;
import info.wegosoft.android.qauth.sina.Weibo;
import info.wegosoft.android.qauth.tencent.OAuth;
import info.wegosoft.android.qauth.tencent.QWeiboAsyncApi;
import info.wegosoft.android.qauth.tencent.QWeiboType.ResultType;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Looper;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Media;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

/**  
 * Filename:    WriteMicroBlogActivity.java 
 * Package:     info.wegosoft.android.activity 
 * Description: 写新微博Activity
 * Copyright:   Copyright (c) wegosoft.info 2011  
 * @author:     李辉 
 * email:       fzlihui@gmail.com
 * @version:    1.0  
 * Create at:   2011-5-17 上午10:33:08  
 */
public class WriteMBlogActivity extends Activity {
	
	private ProgressDialog sendProgressDialog;
	private ImageButton backBtn;
	private ImageButton insertImageButton;
	private ImageView insertPic;
	private TextView text_limit;
	private Button sendButton;
	private EditText microBlog_ed;
	private LinearLayout delword_ll;
	private File imageFile = null;
	//缓存在本地的上传拍照图片文件夹，如果此处写成程序路径则拍照以后不会调用onActivityResult，原因是外部程序无法访问本程序
	private File TEMP_IMG_DIR = null;  
	
    public void onCreate(Bundle savedInstanceState) {
		
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.write_mblog);
        
//        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        
        TEMP_IMG_DIR = new File(Environment.getExternalStorageDirectory() + getResources().getString(R.string.upload_camera_dir_path));

        //字数限制提醒
        text_limit = (TextView) findViewById(R.id.text_limit);

        //编辑框
        microBlog_ed = (EditText) findViewById(R.id.microBlog_ed);
        
        microBlog_ed.addTextChangedListener(new TextWatcher() {
			
			public void onTextChanged(CharSequence s, int start, int before, int count) {}
			
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
			
			public void afterTextChanged(Editable s) {

				int charNum = microBlog_ed.getText().length();
				
				text_limit.setText("" + (140 - charNum));
			}
		});
        
        //删除所有文字的布局
        delword_ll = (LinearLayout) findViewById(R.id.delword_ll);
        
        delword_ll.setOnClickListener(new OnClickListener() {			

        	public void onClick(View v) {
				
        		new AlertDialog.Builder(WriteMBlogActivity.this)
				.setMessage("是否要删除所有文字?")
				.setPositiveButton("确定",
						new DialogInterface.OnClickListener() {
					
							public void onClick(DialogInterface dialog,
									int which) {

								text_limit.setText("" + 140);
								
								microBlog_ed.setText("");
							}
						}).setNegativeButton("返回", null).show();
				
			}
		});
        
        //插入状态的图片
        insertPic = (ImageView) findViewById(R.id.insertPic);
        
		insertPic.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				new AlertDialog.Builder(WriteMBlogActivity.this)
						.setMessage("是否要删除这张图片?")
						.setPositiveButton("确定",
								new DialogInterface.OnClickListener() {
							
									public void onClick(DialogInterface dialog,
											int which) {
										
										imageFile = null;
										
										insertPic.setVisibility(View.GONE);
										
									}
								}).setNegativeButton("返回", null).show();

			}
		});
        
		//后退按钮
        backBtn = (ImageButton) findViewById(R.id.writeBackBtn);
        
        backBtn.setOnClickListener(new OnClickListener() {			

        	public void onClick(View v) {
				
				returnToHome();
				
			}
		});
        
        //发送按钮
        sendButton = (Button) findViewById(R.id.sendBtn); 
        
        sendButton.setOnClickListener(new OnClickListener() {			

        	public void onClick(View v) {
				
        		if(microBlog_ed.getText().toString().trim().length() == 0){
        			
        			Toast.makeText(WriteMBlogActivity.this, "说些什么吧", Toast.LENGTH_SHORT).show();
        			
        		}else{
        			
        			sendText();
        			
        		}
			}
		});
        
        
        
        insertImageButton = (ImageButton) findViewById(R.id.insert_pic_btn);
        
        insertImageButton.setOnClickListener(new OnClickListener() {			

        	public void onClick(View v) {
				
        		new AlertDialog.Builder(WriteMBlogActivity.this).setTitle("选择上传方式").setItems(R.array.uploadImages,
						
        				new DialogInterface.OnClickListener() { 
							
							public void onClick(DialogInterface dialog, int which) {

								String[] array = getResources().getStringArray(R.array.uploadImages); 
								
								System.out.println("上传方式：" + array[which]);
												
								switch (which) {
									case 0:
										
										getCameraPicture();
										
										break;
										
									case 1:
										
										getLocalImage();
										
										break;
										
									default:
										break;
								}
							}

        		}).setNegativeButton("返回",null).show();
				
			}
		});
    }


	/**
	 * 跳转到相机
	 */
	private void getCameraPicture(){
		//创建上传照片的临时存储目录  
		TEMP_IMG_DIR.mkdirs();
		
		// 给新照的照片文件命名  
		imageFile = new File(TEMP_IMG_DIR, System.currentTimeMillis() + ".jpg");
		
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE, null);  
        
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(imageFile));
		
		//取得相片后返回本画面 
        startActivityForResult(intent, CAMERA);  
	}
	
	/**
	 * 跳转到本地图片上传
	 */
	private void getLocalImage(){
		
		 Intent intent = new Intent();  
         
		 //开启Pictures画面Type设定为image
         intent.setType("image/*");  
         
         //使用Intent.ACTION_GET_CONTENT这个Action
         intent.setAction(Intent.ACTION_GET_CONTENT);   
         
         //取得相片后返回本画面 
         startActivityForResult(intent, LOCAL_IMAGE);  
	}
	
	private static final int LOCAL_IMAGE = 1;
	private static final int CAMERA = 2;
	/**
	 * 处理获取图片后的返回
	 */
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
        
		if (resultCode == RESULT_OK) { 
        	
			Bitmap bitmap = null;
			
			switch (requestCode) {
				case LOCAL_IMAGE:
					
					Uri uri = data.getData();  
                    
		            System.out.println("上传图片的uri路径：" + uri.getPath());
		            
					try {
						
						String[] proj = { MediaStore.Images.Media.DATA };
						
						Cursor actualimagecursor = managedQuery(uri,proj,null,null,null);
						
						int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); 
						
						actualimagecursor.moveToFirst();
						
						String img_path = actualimagecursor.getString(actual_image_column_index);
						
						imageFile = new File(img_path);
						
						System.out.println("上传图片的本地路径：" + img_path);
						
//						InputStream is = this.getContentResolver().openInputStream(uri);
//						
//						//byte数组为新浪准备
//						imageFileBytes = new byte[is.available()];
//						                        
//						is.read(imageFileBytes);  
			            
						bitmap = Media.getBitmap(this.getContentResolver(), uri);
										
					} catch (FileNotFoundException e) {
						
						e.printStackTrace();
						
					} catch (IOException e) {
						
						e.printStackTrace();
						
					}  
					
					break;
					
				case CAMERA:
						
					System.out.println("上传图片的本地路径：" + imageFile.getAbsolutePath());
				
					bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
					
//					try {
//						FileInputStream fis = new FileInputStream(imageFile);
//					
//						if (fis != null) {
//							
//							int len = fis.available();
//							
//							imageFileBytes = new byte[len];
//							
//							fis.read(imageFileBytes);
//						}
//						
//					} catch (FileNotFoundException e) {
//						
//						Toast.makeText(WriteMicroBlogActivity.this, "照片获取失败", Toast.LENGTH_SHORT).show();
//						
//						imageFile = null;
//						
//						imageFileBytes = null;
//						
//						e.printStackTrace();
//						
//						return;
//						
//					} catch (IOException e) {
//						
//						Toast.makeText(WriteMicroBlogActivity.this, "照片获取失败", Toast.LENGTH_SHORT).show();
//						
//						imageFile = null;
//						
//						imageFileBytes = null;
//						
//						e.printStackTrace();
//						
//						return;
//					}
		            
					break;
					
				default:
					break;
			}
			     
            //将获取的图片显示在缩略图中
			insertPic.setImageBitmap(bitmap);  
            
			insertPic.setVisibility(View.VISIBLE);
        }  
		
        super.onActivityResult(requestCode, resultCode, data);  
        
    }  
	
	private void returnToHome(){
		
		Intent intent = new Intent();
		
		intent.setClass(WriteMBlogActivity.this, HomeTabsActivity.class);
		
		WriteMBlogActivity.this.finish();
		
		startActivity(intent);
	}
	
	
	private void sendText(){
		
		final String text = microBlog_ed.getText().toString();
		
		System.out.println(text);
		
		int platformType = this.getSharedPreferences("platform",Context.MODE_PRIVATE).getInt("type", -1);
		
		
		switch (platformType) {
			case Platform.SINA_PLATFORM:
				 
				 this.sendToSina(text);
				 
				 break;
			case Platform.TENCENT_PLATFORM:
				 
				 this.sendToTencent(text);
				 
				 break;	
			default:
				 break;
		}
		
	}
	
	private void sendToSina(final String text){
		
		sendProgressDialog = ProgressDialog.show(WriteMBlogActivity.this,null,"发布中",true);
		    
		new Thread()
	    { 
	        public void run()
	        {     
	        	//在线程中绘制toast，一定要调用Looper.prepare()和Looper.loop()，不然会报异常
	        	//ERROR/AndroidRuntime(10325): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
	        	Looper.prepare();     
	        	 
	        	try {
	        		
	        		Weibo weibo = OAuthConstant.getInstance().getWeibo();	
	        		
	        		//上传包含图片的状态
	        		if(imageFile != null){
	        			
	        			String url = java.net.URLEncoder.encode(text,"UTF-8");
	        					
	        			weibo.uploadStatus(url, imageFile);
	        			    		
	        		}else{
	        			
	        			weibo.updateStatus(text);
	        			
	        		}
     		
	    			sendProgressDialog.dismiss(); 
      		
	    			Toast.makeText(WriteMBlogActivity.this, "发布成功", Toast.LENGTH_SHORT).show();
	    			
	    			returnToHome();
	    			
	    		} catch (Exception e) {
	    			
	    			sendProgressDialog.dismiss(); 
	    			
	    			Toast.makeText(WriteMBlogActivity.this, "发布失败", Toast.LENGTH_SHORT).show();
	    			
					e.printStackTrace();
				}
	    		
	    		Looper.loop();	   
	        }
	    }.start(); //开始运行运行线程 	
	}
	
	private void sendToTencent(final String text){
		
		sendProgressDialog = ProgressDialog.show(WriteMBlogActivity.this,null,"发布中",true);
		
		new Thread()
	    { 
	        public void run()
	        { 
	        	
	        	Looper.prepare(); 
     	
	        	SharedPreferences preference = getSharedPreferences("tencent_qauth",Context.MODE_PRIVATE);
	    		
	    		QWeiboAsyncApi api = new QWeiboAsyncApi();
	    		
	    		String imagePath = null;
	    		
	    		if(imageFile != null){
        			
        			imagePath = imageFile.getAbsolutePath();
        		
        		}
	    		
	    		if(!api.publishMsg(OAuth.AppKey, OAuth.AppSecret,preference.getString("AccessToken", null),preference.getString("AccessTokenSecret", null), text, imagePath , ResultType.ResultType_Json))
	    		{
	    			sendProgressDialog.dismiss(); 
	    			
	    			Toast.makeText(WriteMBlogActivity.this, "发布失败", Toast.LENGTH_SHORT).show();
	    		
	    		}else{
	    			
	    			Toast.makeText(WriteMBlogActivity.this, "发布成功", Toast.LENGTH_SHORT).show();
	    			
	    			returnToHome();
	    			
	    		}
	    		
	    		Looper.loop();	   
	        }
	    }.start();
	
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK) {

			this.finish();

		}

		return super.onKeyDown(keyCode, event);
	}
}
